﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Diagnostics;

public partial class restaurant_adddish : System.Web.UI.Page
{
    private class IngredientTemplate : ITemplate
    {
        static int itemcount = 1;
        public void InstantiateIn(System.Web.UI.Control container)
        {
            Literal lc = new Literal();
            lc.Text = "Item number: " + itemcount.ToString();
            itemcount += 1;

            TextBox nameTextBox = new TextBox();
            nameTextBox.DataBinding += new EventHandler(TemplateControl_NameDataBinding);

            TextBox descTextBox = new TextBox();
            descTextBox.DataBinding += new EventHandler(TemplateControl_DescDataBinding);

            container.Controls.Add(lc);
            container.Controls.Add(nameTextBox);
            container.Controls.Add(descTextBox);
        }
        private void TemplateControl_NameDataBinding(object sender, EventArgs e)
        {
            TextBox nameTextBox;
            nameTextBox = (TextBox)sender;
            RepeaterItem container = (RepeaterItem)nameTextBox.NamingContainer;
            nameTextBox.Text += DataBinder.Eval(container.DataItem, "Name");
        }
        private void TemplateControl_DescDataBinding(object sender, EventArgs e)
        {
            TextBox descTextBox;
            descTextBox = (TextBox)sender;
            RepeaterItem container = (RepeaterItem)descTextBox.NamingContainer;
            descTextBox.Text += DataBinder.Eval(container.DataItem, "Description");
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            InitData(true);
        }
    }
    protected void InitData(bool initForm)
    {
        Int16 restaurantId = 0;
        if (Session["restaurant_id"] == null
            || !Int16.TryParse(Session["restaurant_id"].ToString(), out restaurantId))
            return;

        // InitCategoryDishes
        Entities.Restaurant restaurant = new Entities.Restaurant(restaurantId);
        category_repeater.DataSource = restaurant.Menu.Categories;
        category_repeater.DataBind();

        // InitForm
        if (initForm)
        {
            category_dropdownlist.DataBound += new EventHandler(MyListDataBound);
            category_dropdownlist.DataSource = restaurant.Menu.Categories;
            category_dropdownlist.DataBind();
        }
    }
    protected void MyListDataBound(object sender, EventArgs e)
    {
        category_dropdownlist.Items.Insert(0, new ListItem("--选择分类--", "--选择分类--"));
    }

    protected void UpdateNotice(String notice, bool isWarning)
    {
        notice_label.Text = notice;

        if (isWarning)
            notice_label.ForeColor = System.Drawing.Color.Red;
    }
    // collect the ingredient from the webcontrol into the Dish object
    protected void CollectIngredients(ref List<Entities.Ingredient> ingredients)
    {
        // Go through the repeater to get the old data,
        //for (int i = samilar_dishes_datagrid.Items.Count - 1; i >= 0; i--)
        //{
        //    String name = ((TextBox)samilar_dishes_datagrid.Items[i].FindControl("ingredient_name")).Text;
        //    String description = ((TextBox)samilar_dishes_datagrid.Items[i].FindControl("ingredient_desc")).Text;
        //    Entities.Ingredient ingredient = new Entities.Ingredient();
        //    ingredient.Name = name;
        //    ingredient.Description = description;
        //    ingredients.Add(ingredient);
        //}
    }
    protected void OnDishTextChanged(object sender, EventArgs e)
    {
        List<Entities.Dish> similarDishes = null;

        // Reset the dishId label
        similar_dish_id_label.Text = "";
        dishdisc_textbox.Enabled = true;
        TextBox textbox = (TextBox)sender;
        String dishName = textbox.Text.Trim();
        if (dishName.Length >= 2
            && null != (similarDishes = BLL.Command.DishesWithSimilarName(dishName))
            && similarDishes.Count > 0)
        {
            for (int i = 0; i < similarDishes.Count; i++)
                similarDishes[i].Name += "\t" + similarDishes[i].Description;

            similar_dishes_listbox.Visible = true;
            similar_dishes_label.Visible = true;
            similar_dishes_listbox.DataSource = similarDishes;
            similar_dishes_listbox.DataBind();
        }
        else
        {
            similar_dishes_listbox.Visible = false;
            similar_dishes_label.Visible = false;
        }
    }
    protected void OnSelectedSimilarDishChanged(Object sender, EventArgs e)
    {
        dishdisc_textbox.Enabled = false;
        ListBox listbox = (ListBox)sender;

        Int16 dishId = Convert.ToInt16(listbox.SelectedValue);
        String selectedText = listbox.SelectedItem.Text;
        String[] columns = selectedText.Split('\t');
        String Name = columns[0];
        String Description = columns[1];

        similar_dish_id_label.Text = dishId.ToString();
        dishname_textbox.Text = Name;
        dishdisc_textbox.Text = Description;
    }
    protected void OnClickAddIngredientBtn(object sender, EventArgs e)
    {
        //List<Entities.Ingredient> ingredients = new List<Entities.Ingredient>();
        //CollectIngredients(ref ingredients);

        ////// then add a new empty record
        //ingredients.Add(new Entities.Ingredient());

        //samilar_dishes_datagrid.DataSource = ingredients;
        //samilar_dishes_datagrid.DataBind();
    }
    protected void OnClickAddCategory(object sender, EventArgs e)
    {
        if (Session["restaurant_id"] == null)
            return;

        Int16 restaurantId = 0;
        if (!Int16.TryParse(Session["restaurant_id"].ToString(), out restaurantId))
            return;

        String categoryName = category_name_textbox.Text.Trim();
        String categoryDescription = category_description_textbox.Text.Trim();
        Entities.Category category = new Entities.Category();
        category.RestaurantId = restaurantId;
        category.Name = categoryName;
        category.Description = categoryDescription;

        if (BLL.Command.NewCategory(ref category))
        {
            UpdateNotice("新菜单分类创建成功！", false);
            InitData(true);
        }
        else
            UpdateNotice("新菜单分类创建失败！！！", true);
    }
    protected void OnClickManualAddBtn(object sender, EventArgs e)
    {        
        Entities.CagetoryDish categoryDish = new Entities.CagetoryDish();
        categoryDish.CategoryId = Convert.ToInt16(category_dropdownlist.SelectedValue);

        Double price = 0.0;
        if (!Double.TryParse(price_textbox.Text.Trim(), out price))
        {
            UpdateNotice("请输入有效的菜品价格!", true);
            return;
        }
        categoryDish.Price = price;
        Entities.Dish dish = null;
        Int16 dishId=0;
        Int16.TryParse(similar_dish_id_label.Text, out dishId);

        if (dishId==0 && null == (dish=BLL.Command.GetDishByName(dishname_textbox.Text.Trim())))
        {
            //CollectIngredients(ref dish.Ingredients);
            dish = new Entities.Dish();
            dish.Name = dishname_textbox.Text.Trim();
            dish.Description = dishdisc_textbox.Text.Trim();
            BLL.Command.NewDish(ref dish);
        }

        categoryDish.DishId = dishId==0 ? dish.Id : dishId;
        categoryDish.Name = dishname_textbox.Text.Trim();
        if (BLL.Command.NewCategoryDish(ref categoryDish))
        {
            InitData(false);
            UpdateNotice(categoryDish.Name + " 成功添加!", false);
        }
        else
            UpdateNotice(categoryDish.Name + " 添加到你的餐厅失败,或已存在!!!", true);
    }
    protected void OnClickDelAtMenuBtn(object sender, EventArgs e)
    {
        int dishCounter = 0;
        int categoryCounter = 0;

        for (int i = category_repeater.Items.Count - 1; i >= 0; --i)
        {
            // Del the category, all dishes under will be deleted by trigger.
            CheckBox cb = (CheckBox)category_repeater.Items[i].FindControl("choose_checkbox");
            if (cb.Checked)
            {
                Label hiddenLabel = (Label)category_repeater.Items[i].FindControl("category_id_label");
                Int16 categoryId = Convert.ToInt16(hiddenLabel.Text);
                BLL.Command.DelCategory(categoryId);
                ++categoryCounter;
                continue;
            }

            DataList categoryDishDishList = (DataList)category_repeater.Items[i].FindControl("categorydish_datalist");
            for (int j = categoryDishDishList.Items.Count - 1; j >= 0; --j)
            {
                CheckBox cb2 = (CheckBox)categoryDishDishList.Items[j].FindControl("choose_checkbox");
                if (cb2.Checked)
                {
                    Int16 categoryDishId = Convert.ToInt16(categoryDishDishList.DataKeys[j].ToString());
                    if (BLL.Command.DelCategoryDish(categoryDishId))
                        ++dishCounter;
                }
            }
        }

        if (categoryCounter > 0 || dishCounter > 0)
            InitData(categoryCounter > 0);

        String msg = dishCounter.ToString() + "个菜删除成功!";
        if (categoryCounter > 0)
            msg += " " + categoryCounter + "个分类除成功!";
        UpdateNotice(msg, false);
    }
    
}
